package cn.lingyangwl.agile.msg.push.core.sender;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import cn.lingyangwl.agile.msg.push.api.model.content.*;
import cn.lingyangwl.agile.msg.push.core.*;
import cn.lingyangwl.agile.msg.push.core.channel.*;
import cn.lingyangwl.agile.msg.push.core.channel.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
public class WxMaSender implements MsgSender {
    @Resource
    private ChannelClientManager channelClientManager;

    @Override
    public void sendMessage(PushTaskContext context) {
        MsgSettings msgSettings = context.getMsgSettings();

        context.setChannelCode(ChannelCodeEnum.WX_MINI_APP);
        log.info("send msg to wx_mini_app, msgPush: {}", context);
        MsgParam msgParam = context.getMsgParam();
        List<WxMaSubscribeMessage.MsgData> data = new ArrayList<>();

        msgSettings.getTplField().values().forEach(e -> data.add(new WxMaSubscribeMessage.MsgData(e.getKey(), String.valueOf(e.getValue()))));
        WxMaSubscribeMessage subscribeMessage = WxMaSubscribeMessage.builder()
                        //这里添加的是推送消息的目标对象openId
                        .toUser(msgParam.getToUser())
                        //这里填写的就是在后台申请添加的模板ID
                        .templateId(msgSettings.getTemplateId())
                        //添加请求参数
                        .data(data)
                        //添加跳转链接，如果目标用户点击了推送的消息，则会跳转到小程序主页
                        .page(msgParam.getPageUrl())
                        .build();
        try {
            // 推送消息
            WxMaMsgClient wxMaMsgClient = (WxMaMsgClient) channelClientManager.getChannelClient(context.getChannelType());
            wxMaMsgClient.getWxMaService().getMsgService().sendSubscribeMsg(subscribeMessage);
            context.setChannelCode(wxMaMsgClient.channelCode());
        } catch (Exception e) {
            log.error("模板消息推送失败", e);
            context.setPushStatus(MsgPushStatus.FAIL);
            context.setPushResult(e.getMessage());
        }
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.WX_MINI_APP;
    }
}
